package com.zkingsoft.laqeelin.service.impl;



import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.matrix.core.exception.GlobleException;
import com.matrix.core.tools.LogUtil;
import com.zkingsoft.laqeelin.bean.TemplateData;
import com.zkingsoft.laqeelin.bean.WxTemplate;
import com.zkingsoft.laqeelin.bean.WxTemplateDate;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.common.constance.AppMessageCode;
import com.zkingsoft.laqeelin.service.WxMsgTemplateService;
import com.zkingsoft.tools.Constants;
import com.zkingsoft.tools.HttpRequest;
import com.zkingsoft.tools.HttpResponse;


/**
 * This field was generated by Zking.software.Codegen.
 * @date 2017-08-21 17:05
 */
@Service("WxMsgTemplateServices")
public class  WxMsgTemplateServiceImpl implements WxMsgTemplateService  {
	
	Logger log = Logger.getLogger(WxMsgTemplateServiceImpl.class);
	

	/**
	 * 发送审核通知
	 */
	@Override
	public int xcxTemMsg(WxTemplateDate temDate) {
		if(temDate==null || StringUtils.isBlank(temDate.getOpenId())){
			return 0;
		}
		HttpRequest reqObj = new HttpRequest();
    	HttpResponse result = null;
    	LogUtil.debug("openIdUrl request start!");
		try {
			//result = reqObj.sendHttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+Constants.APPID+"&secret="+Constants.APPSECRET, null);
			result = reqObj.sendHttpGet(Constants.GET_ACCESS_TOKEN_WITHOUTAUTH.replace("APPID", Constants.APPID).replace("APPSECRET", Constants.APPSECRET), null);
			JSONObject json = JSONObject.fromObject(result.getDataString());
			String access_token = json.getString("access_token");
	    	//JSONObject json =null;
	    	//String access_token =  AccessToken.getAccessToken();
			LogUtil.debug("openIdUrl request end! + access_token :{} ", access_token);
			//发送模板URL
	        String url = Constants.XCX_TEMPLATEMSG_SEN.replace("ACCESS_TOKEN", access_token);
	        WxTemplate temp = new WxTemplate();
	        //模板跳转链接
	        temp.setPage(temDate.getUrl());
	        temp.setTouser(temDate.getOpenId());
	        temp.setColor(AppConstance.TEMP_COLOR1);
	        temp.setForm_id(temDate.getFormId());
	        temp.setTemplate_id(temDate.getTemplateId());
	      //消息模版ID
	        if(StringUtils.isBlank(temDate.getTemplateId())){
	            temp.setTemplate_id(Constants.PRIZE_TEMPLATE_ID);
	        }
	    
	        LogUtil.debug("模板ID:{}", temp.getTemplate_id());
	        Map<String,TemplateData> m = new HashMap<String,TemplateData>();
	      
	        TemplateData keyword1 = new TemplateData();  
	        keyword1.setValue(temDate.getFirstKeywordValue());
	        m.put(AppConstance.TEMP_KEYWORD1, keyword1);
	        if(StringUtils.isNotBlank(temDate.getSecondKeywordValue())){
		         TemplateData keyword2 = new TemplateData();  
		        keyword2.setValue(temDate.getSecondKeywordValue());
		        m.put(AppConstance.TEMP_KEYWORD2, keyword2);
	        }
	        if(StringUtils.isNotBlank(temDate.getThreeKeywordValue())){
	        	  TemplateData keyword3 = new TemplateData();  
	  	        keyword3.setValue(temDate.getThreeKeywordValue());
	  	        m.put(AppConstance.TEMP_KEYWORD3, keyword3);
	        }
	      
	        temp.setData(m);
	        String jsonString = JSONObject.fromObject(temp).toString();
	        try {
	        	
	        	
	        	LogUtil.info("提交数据++++++json:{}",jsonString);
				result = reqObj.sendHttpsPost(url, null, jsonString);
				json = JSONObject.fromObject(result.getDataString());
				LogUtil.info("返回数据++++++json:{}",json);
		        int res = 0;
		        
		        if ( json!=null) {  
		        	res = json.getInt(AppConstance.ERRCODE);
		             if (res!=0) {  
		                //添加远大币发送失败 信息
		            	 LogUtil.info("错误 errcode:{} errmsg:{}",+json.getInt("errcode"),json.getString("errmsg"));  
		              
		             } else{
		            	 return 1;
		             }
		         }
		        LogUtil.info("模板消息发送结果：{}",res);
			} catch (IOException e) {
				LogUtil.error("发送模板消息异常2：", e, "");
				//throw new GlobleException(AppMessageCode.Template.SEND_ERR);
			}
		
		} catch (IOException e) {
			LogUtil.error("发送模板消息异常1：", e, "");
			//throw new GlobleException(AppMessageCode.Template.SEND_ERR);
		}
		
		return 0;
	}
	
/*public static void main(String[] args) throws IOException {
	SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日"); 
	
	System.out.println(format.format(new Date()));
	}*/
}